package com.hugang.juc.cas;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子引用
 * 用AtomicReference来包装这个POJO，使其操作原子化。
 *
 * @author hg
 * @date 2020/8/24 19:32
 */
public class AtomicRefrenceDemo {

    public static void main(String[] args) {
        User jack = new User("jack", 22);
        User lucy = new User("lucy", 21);
        AtomicReference<User> reference = new AtomicReference<>();
        reference.set(jack);

        System.out.println(reference.compareAndSet(jack, lucy) + " " + reference.get());
        System.out.println(reference.compareAndSet(jack, lucy) + " " + reference.get());
    }
}

class User {
    String name;
    int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
